﻿using System;
using Arroguella.Tiles;
using Microsoft.Xna.Framework;

namespace Arroguella.Entities
{
    /// <summary>
    /// This AI Component just wanders aimlessly throughout the dungeon.
    /// There is no rhyme or reason, it just picks a direction and moves, one tile at a time.
    /// </summary>
    public class SimpleWanderingAiComponent : AiComponent
    {
        public override void Update(Tile tile)
        {
            if (Parent != null && Parent is CreatureEntity)
            {
                // Stop wandering when attacked.
                if (Attacked)
                {
                    return;
                }

                DecideIntendedMovementCoordinates(tile.Coords);
            }
        }

        /// <summary>
        /// Randomly decides which of the 8 directions to move, or to stay put.
        /// It may or may not be successful; this is just an intention.
        /// </summary>
        private void DecideIntendedMovementCoordinates(Vector2 currentTileCoordinates)
        {
            int choice = random.Next(0, 9);
            int x = (int)currentTileCoordinates.X;
            int y = (int)currentTileCoordinates.Y;

            switch(choice)
            {
                default:
                case 0: IntendedMovementCoordinates = currentTileCoordinates;    break;   // Stay put
                case 1: IntendedMovementCoordinates = new Vector2(x, y - 1);     break;   // N
                case 2: IntendedMovementCoordinates = new Vector2(x + 1, y - 1); break;   // NW
                case 3: IntendedMovementCoordinates = new Vector2(x + 1, y);     break;   // W
                case 4: IntendedMovementCoordinates = new Vector2(x + 1, y + 1); break;   // SW
                case 5: IntendedMovementCoordinates = new Vector2(x, y + 1);     break;   // S
                case 6: IntendedMovementCoordinates = new Vector2(x - 1, y + 1); break;   // SE
                case 7: IntendedMovementCoordinates = new Vector2(x - 1, y);     break;   // E
                case 8: IntendedMovementCoordinates = new Vector2(x - 1, y - 1); break;   // NE
            }
        }

        /// <summary>
        /// The TileCoordinates that this Ai intends to move to next.
        /// Whether or not it is successful is up to the TileEngine.
        /// </summary>
        public Vector2 IntendedMovementCoordinates { get; set; }

        private readonly Random random = new Random();
    }
}
